package com.sam.library.document;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author wanghao
 * @date 2022/11/1.
 * @des
 */
public class HeaderAdapter extends RecyclerView.Adapter<HeaderAdapter.ViewHolder> implements View.OnClickListener {

    private List<File> mFiles;
    private LayoutInflater mLayoutInflater;

    private OnDirectoryClickListener listener;

    public HeaderAdapter(OnDirectoryClickListener listener) {
        this.listener = listener;
    }

    public void setData(File dir) {
        mFiles = new ArrayList<>();
        do {
            mFiles.add(dir);
            dir = dir.getParentFile();
        } while (dir != null && dir.listFiles() != null && dir.listFiles().length > 0);
        Collections.reverse(mFiles);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        initInflater(parent);
        View view = mLayoutInflater.inflate(R.layout._sam_document_header, parent, false);
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    private void initInflater(ViewGroup parent) {
        if (mLayoutInflater == null) {
            long t = System.currentTimeMillis();
            mLayoutInflater = LayoutInflater.from(parent.getContext());
            Log.e("TAG", "initInflater: " + (System.currentTimeMillis() - t));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.itemView.setTag(position);
        holder.title.setText(mFiles.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mFiles == null ? 0 : mFiles.size();
    }

    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        File file = mFiles.get(position);
        if (listener != null && file.isDirectory()) {
            listener.onDirectoryClick(file);
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        TextView title;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.tv);
        }
    }

}
